<template>
  <el-card>
    <template #header>
      <h2>日常护理管理</h2>
    </template>

    <!-- 客户搜索 -->
    <el-form inline class="toolbar">
      <el-form-item label="客户姓名">
        <el-input v-model="filters.name" placeholder="模糊搜索客户" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearchCustomers">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 客户列表 -->
    <el-table :data="customers" stripe border style="margin-top: 16px">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="name" label="客户姓名" width="100" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column label="性别" width="80">
        <template #default="{ row }">
          <span>{{ row.gender === 0 ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="roomNumber" label="房间号" width="60" />
      <el-table-column prop="bedNumber" label="床号" />
      <el-table-column prop="careLevelName" label="护理级别" width="120" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openCareProjectDialog(row)">日常护理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 客户分页 -->
    <el-pagination
      class="mt-4"
      style="text-align:right;"
      :current-page="customerPage"
      :page-size="customerSize"
      :page-sizes="[5,10,20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="customerTotal"
      @current-change="onCustomerPageChange"
      @size-change="onCustomerSizeChange"
    />

    <!-- 护理项目弹窗 -->
    <el-dialog v-model="projectDialogVisible" title="客户护理项目" width="60%">
      <el-table :data="careProjects" stripe border style="margin-bottom: 16px">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="careProjectCode" label="项目代码" />
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="quantity" label="余量" />
        <el-table-column prop="expireDate" label="到期日" />
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button size="small" @click="openRecordDialog(row)">添加记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="projectTotal > 0"
        class="mt-4"
        style="text-align:right;"
        :current-page="projectPage"
        :page-size="projectSize"
        :page-sizes="[5,10,20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="projectTotal"
        @current-change="onProjectPageChange"
        @size-change="onProjectSizeChange"
      />
    </el-dialog>

    <!-- 添加护理记录弹窗 -->
    <el-dialog v-model="recordDialogVisible" title="添加护理记录" width="500px">
      <el-form :model="recordForm" label-width="100px" ref="recordFormRef">
        <!-- 只读显示项目代码、名称和单价 -->
        <el-form-item label="项目代码">
          <el-input v-model="recordForm.careProjectCode" disabled />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="recordForm.projectName" disabled />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="recordForm.price" disabled />
        </el-form-item>

        <!-- 可填写字段 -->
        <el-form-item label="护理时间" prop="careTime" :rules="[{ required: true }]">
          <el-date-picker
            v-model="recordForm.careTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择时间"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="数量" prop="quantity" :rules="[{ required: true }]">
          <el-input-number v-model="recordForm.quantity" :min="1" style="width:100%" />
        </el-form-item>
        <el-form-item label="护理内容">
          <el-input type="textarea" v-model="recordForm.content" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="recordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRecord">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, inject, watch } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { jwtDecode } from 'jwt-decode'

const axios = inject('axios')
const nurseId = ref('')

// 初始化获取健康管家ID
const init = () => {
  const token = sessionStorage.getItem('token')
  const payload = jwtDecode(token)
  const user = JSON.parse(payload.mobileJson)
  nurseId.value = user.id
}
init()

// 客户列表
const filters = reactive({ name: '' })
const customers = ref([])
const customerPage = ref(1)
const customerSize = ref(10)
const customerTotal = ref(0)

const fetchCustomers = () => {
  axios.post(
    'CheckOutRegistrationController/searchClient',
    qs.stringify({
      healthManagerId: nurseId.value,
      clientName: filters.name,
      cur: customerPage.value,
      number: customerSize.value,
    })
  )
    .then(res => {
      const rb = res.data
      if (rb.status === 200) {
        customers.value = rb.data
        customerTotal.value = rb.total
      } else {
        ElMessage.error('加载失败：' + rb.message)
      }
    })
}

const onSearchCustomers = () => { customerPage.value = 1; fetchCustomers() }
const onCustomerPageChange = p => { customerPage.value = p; fetchCustomers() }
const onCustomerSizeChange = s => { customerSize.value = s; customerPage.value = 1; fetchCustomers() }

// 护理项目弹窗
const projectDialogVisible = ref(false)
const careProjects = ref([])
const projectPage = ref(1)
const projectSize = ref(5)
const projectTotal = ref(0)
let currentCustomerId = null

// 关闭时重置
watch(projectDialogVisible, val => {
  if (!val) {
    projectPage.value = 1;
    projectSize.value = 5;
    careProjects.value = [];
    currentCustomerId = null;
  }
});

function fetchCareProjects() {
  axios.get('/CustomerCarePlanController/searchCustomerCarePlanPage', {
    params: {
      customerId: currentCustomerId,
      cur:        projectPage.value,
      number:     projectSize.value
    }
  }).then(res => {
    const rb = res.data;
    if (rb.status === 200) {
      careProjects.value = rb.data;
      projectTotal.value  = rb.total;
    } else {
      ElMessage.error(rb.message);
    }
  });
}

// 打开弹窗（只做一次 row => id 赋值 + 重置分页 + 调用）
const openCareProjectDialog = row => {
  currentCustomerId      = row.id;
  projectPage.value      = 1;
  projectSize.value      = 5;
  careProjects.value     = [];
  projectDialogVisible.value = true;
  fetchCareProjects();
};


// 翻页只调用 fetch
const onProjectPageChange = p => {
  projectPage.value = p;
  fetchCareProjects();
};
const onProjectSizeChange = s => {
  projectSize.value = s;
  projectPage.value = 1;
  fetchCareProjects();
};

// 添加护理记录
const recordDialogVisible = ref(false)
const recordFormRef = ref(null)
const recordForm = reactive({ careProjectCode: '', projectName: '', price: '', careTime: '', quantity: 1, content: '' })
let currentProject = null

const openRecordDialog = proj => {
	console.log('selected project:', proj)
  currentProject = proj
  // 填充只读项目数据
  recordForm.careProjectCode = proj.careProjectCode
  recordForm.projectName = proj.projectName
  recordForm.price = proj.price
  recordForm.careTime = ''
  recordForm.quantity = 1
  recordForm.content = ''
  recordDialogVisible.value = true
}

const submitRecord = () => {
  axios.post('/CareRecordController/addCareRecord', qs.stringify({
    customerId: currentCustomerId,
    careProjectId: currentProject.projectId,
    careStaffId: nurseId.value,
    careTime: recordForm.careTime,
    quantity: recordForm.quantity,
    content: recordForm.content
  }))
    .then(res => {
      const rb = res.data
      if (rb.status === 200) {
        ElMessage.success('记录已保存')
        recordDialogVisible.value = false
        // 减少余量
        careProjects.value.forEach(p => {
          if (p.projectId === currentProject.projectId) {
            p.quantity -= recordForm.quantity
          }
        })
      } else ElMessage.error(rb.message)
    })
} 

fetchCustomers()
</script>

<style scoped>
.toolbar { margin-bottom: 16px }
.mt-4 { margin-top: 16px }
</style>
